<?php
/**
 * Created by PhpStorm.
 * User: gakuin
 * Date: 7/8/16
 * Time: 4:03 PM
 */
namespace app\controllers;

use yii;
use yii\helpers\Url;
use app\models\Proxy;
use app\models\Borkerage;
use app\models\ProxyApply;
use app\models\User;
use app\models\Upload;
use yii\web\UploadedFile;

class LowgradeController extends  BackbaseController
{

//    独立的layout
    public $layout  = 'lowgrade';


//   我的佣金的
    public function actionMybroke(){
        $view = Yii::$app->view;
        $view->params['menuitemid'] = 11;
        return $this -> render('myborke');

    }
//    二级佣金界面
    public function actionMainview(){

        $view = Yii::$app->view;
        $view->params['menuitemid'] = 12;
        return $this -> render('secondagent');

    }

//     三级佣金界面
    public function actionThirdagent(){
        $view = Yii::$app->view;
        $view->params['menuitemid'] = 13;
        return $this -> render('thirdagent');

    }

//    代理申请界面
    public function actionAccept(){
        $view = Yii::$app->view;
        $view->params['menuitemid'] = 21;
        return $this -> render('acceptagent');

    }

//    代理管理界面
    public function actionDeal(){
        $view = Yii::$app->view;
        $view->params['menuitemid'] = 22;
        return $this -> render('dealagent');

    }

    public function actionAllgrades(){

        $userid = \Yii::$app->user->id;
        $allgrade = 0;
        $order = Borkerage::getorder($userid);
        foreach($order as $key=>$value) {
            $allgrade = $allgrade + $value['brokerage_money'];
        }
        return json_encode(['allmoney' => $allgrade]);
    }


    public function actionShareurl(){

        $view = Yii::$app->view;
        $view->params['menuitemid'] = 31;
        
        $baseUrl=Url::home(true);
        $userid = \Yii::$app->user->id;
        return $this->render('shareurl',['model' => $userid,'baseUrl'=>$baseUrl]);
    }

    public function actionMybrokeordes(){


        $userid = \Yii::$app->user->id;

        $totalarray = null;

        $order = Borkerage::getorder($userid);

        foreach($order as $key=>$value) {

            $currentI = count($totalarray);
            $totalarray[$currentI] = [

                'orderform_id' => $value['orderform_id'],
                'orderform_money' => $value['orderform_money'],
                'brokerage_money' => $value['brokerage_money'],
                'user_id' => $value['user_id'],
                'create_time' => $value['create_time']

            ];
        }

        echo $this -> dealemptyary($totalarray);
    }


    // 二级代理商的佣金表的url
    public function actionSecondgrade(){

        $userid = \Yii::$app->user->id;
        $statusarray =  Proxy::getsonrarray($userid);
        $totalarray = null;
        $num = count($statusarray);

        for($i=0;$i<$num;++$i){
            $order = Borkerage::getorder($statusarray[$i]['user_id']);
            foreach($order as $key=>$value){
                $currentI =  count($totalarray);

                $user =  User::find() -> where(['user_id'=> [$value['user_id']]])->asArray()->one();

                $totalarray[$currentI] = [

                    'orderform_id' => $value['orderform_id'],
                    'orderform_money' => $value['orderform_money'],
                    'brokerage_money' => $value['brokerage_money'],
                    'user_id' => $value['user_id'],
                    'create_time' => $value['create_time'],
                    'username' => $user['username']
                ];
            }

        }

        return $this -> dealemptyary($totalarray);
    }

    // 三级代理商的佣金表的url
    public function actionThirdgrage(){

        $totalarray = null;
        $userid = \Yii::$app->user->id;
        $secondary =  Proxy::getsonrarray($userid);
        $num = count($secondary);

        for($i=0;$i<$num;++$i){

            $thirdary = Proxy::getsonrarray($secondary[$i]['user_id']);
            $thirdnum = count($thirdary);


            for($j=0;$j<$thirdnum;++$j) {

                $order = Borkerage::getorder($thirdary[$j]['user_id']);
                $ordernum = count($order);

                for($z=0;$z<$ordernum;++$z) {

                    $currentI = count($totalarray);

                    $user =  User::find() -> where(['user_id'=> [$order[$z]['user_id']]])->asArray()->one();

                    $totalarray[$currentI] = [

                        'orderform_id' => $order[$z]['orderform_id'],
                        'orderform_money' => $order[$z]['orderform_money'],
                        'brokerage_money' => $order[$z]['brokerage_money'],
                        'user_id' => $order[$z]['user_id'],
                        'create_time' => $order[$z]['create_time'],
                        'username' => $user['username']

                    ];
                }
            }
        }

        return $this -> dealemptyary($totalarray);
    }

    // 同意拒绝代理申请界面的table url
    public function actionAcceptgrade(){

        //获取相应字段
        $request = \Yii::$app->request;
        $offset = $request->get('offset');
        $limit = $request->get('limit');
        $search = $request->get('search');
        $leader_id = \Yii::$app->user->id;

        $model = new ProxyApply();
        $rs = $model->getCheckAgentTableData($limit,$offset,$search,$leader_id);
        echo json_encode($rs);
    }

    //代理申请审批
    public function actionCheckAgentOperate(){

        //获取相应字段
        $request = \Yii::$app->request;
        $apply_id = $request->get('apply_id');
        $status = $request->get('status');

        $model = ProxyApply::findOne(['apply_id'=>$apply_id]);
        $model->status = $status;
        $rs=$model->save();  // 等同于 $model->update();

        if($status==1){
            $apply =  ProxyApply::getcurrent($apply_id);

            \Yii::$app->db->createCommand()->insert('hcps_proxy', [

                'user_id' => $apply['user_id'],
                'leader_id' => $apply['leader_id'],
                'del_flag' => 1,
                'create_time' => date('Y-m-d h:i:s',time()),
                'content' => $apply['content'],
                'mobile' => $apply['mobile'],

            ])->execute();

            User::updateAll(['type' => '1'],['user_id' => [$apply['user_id']]]);
        }else{
            ProxyApply::updateAll(['status'=>'2'],['apply_id' => $apply_id]);
        }

        echo json_encode($rs);

    }


    // 管理代理界面拿到table 的数据
    public function actionMyallgrate(){

        //获取相应字段
        $request = \Yii::$app->request;
        $offset = $request->get('offset');
        $limit = $request->get('limit');
        $search = $request->get('search');
        $leader_id = \Yii::$app->user->id;

        $model = new Proxy();
        $rs = $model->getAgentListTableData($limit,$offset,$search,$leader_id);
        echo json_encode($rs);

    }

    // 撤销代理方法
    public function actionRemovegrate(){

        $request = \Yii::$app->request;
        $currentId = $request->get('user_id');
        Proxy::updateAll(['del_flag' => '0'],['user_id' => $currentId]);//删除改代理
        User::updateAll(['type' => '0'],['user_id' => $currentId]);
        //删除该代理下级代理
        $this->actionRemoveall($currentId);
        //删除该代理及下级代理的佣金关系
        $this->removeAllBrokerageRelations($currentId);

        // ajax 要返回一个正确格式的json 不然不走success方法
        return json_encode(['success' => true]);

    }


    public function actionRemoveall($leaderid){

        $statusArray = Proxy::find() -> where(['leader_id' => $leaderid, 'del_flag' => 1]) -> asArray() -> all();
        $num = count($statusArray);

        for($i=0;$i<$num;$i++){

            Proxy::updateAll(['del_flag' => '0'],['user_id' => $statusArray[$i]['user_id']]);
            User::updateAll(['type' => '0'],['user_id' => [$statusArray[$i]['user_id']]]);

            $this -> actionRemoveall($statusArray[$i]['user_id']);

        }
    }

    private function removeAllBrokerageRelations($agentId) {
         $sql = \Yii::$app->db
            ->createCommand(
                'UPDATE distribution.hcps_brokerage_relationship SET del_flag = 0 WHERE customer_user_id IN
                (SELECT * FROM 
                (SELECT DISTINCT customer_user_id FROM distribution.hcps_brokerage_relationship WHERE agent_user_id = :agent_id AND del_flag = 1) temp
                )')
            ->bindValue(':agent_id', $agentId)
            ->execute();
    }

    public  function  dealemptyary($statusarray){

        $totalCount =  count($statusarray);
        if($totalCount == 0){
            return '';
        }else{
            return json_encode($statusarray);
        }

    }

}